package cn.source.zk.service.impl;

import cn.source.common.constant.UserConstants;
import cn.source.common.utils.SecurityUtils;
import cn.source.common.utils.StringUtils;
import cn.source.zk.domain.entity.Area;
import cn.source.zk.mapper.ZkAreaMapper;
import cn.source.zk.service.IZkAreaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
public class ZkAreaServiceImpl implements IZkAreaService {

    @Autowired
    private ZkAreaMapper areaMapper;

    @Override
    public List<Area> selectAreaList(Area area) {

        // area.setCompanyId(SecurityUtils.getCompanyId());
        List<Area> areas = areaMapper.selectAreaList(area);
        return areas;

    }

    /**
     * 校验地区是否存在
     *
     * @param area
     * @return
     */
    public String checkAreaCodeUnique(Area area) {
        // 校验地区是否存在；
        Long areaId = StringUtils.isNull(area.getNum()) ? -1L : area.getNum();
        Area info = areaMapper.checkAreaNameUnique(area.getName(), area.getParentId(), area.getCode());
        if (StringUtils.isNotNull(info) && info.getNum().longValue() != areaId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }


    /**
     * 插入地区
     *
     * @param area
     * @return
     */
    public int insertArea(Area area) {
        String ancestors = buildAncestors(area.getParentId());
        area.setAncestors(ancestors);
        area.setCreateTime(new Date());
        area.setUpdateTime(new Date());
        area.setCreateBy(SecurityUtils.getUsername());
        area.setUpdateBy(SecurityUtils.getUsername());
        return areaMapper.insertArea(area);
    }


    /**
     * 根据id查询地区
     *
     * @param num
     * @return
     */
    public Area selectById(Long num) {
        return areaMapper.selectById(num);
    }


    /**
     * 修改地区
     *
     * @param area
     * @return
     */
    public int updateArea(Area area) {
        String ancestors = buildAncestors(area.getParentId());
        area.setAncestors(ancestors);

        //查询所有的子部门


        return areaMapper.updateArea(area);
    }


    /**
     * 删除地区
     *
     * @param num
     * @return
     */
    public int remove(Long num) {

        return areaMapper.remove(num);
    }

    /**
     * 是否存在下级部门
     *
     * @param num
     * @return
     */
    public boolean hasChildByNum(Long num) {
        int result = areaMapper.hasChildByNum(num);
        return result > 0;
    }

    // 获取祖级id字符串;
    private String buildAncestors(Long num) {
        StringBuilder ancestorsBuilder = new StringBuilder();
        //传入的参数就是父级ID需要先写入
        ancestorsBuilder.insert(0, num);
        Long parentId = getParentId(num);
        while (parentId != null) {

            ancestorsBuilder.insert(0, parentId + ",");
            parentId = getParentId(parentId);
        }
        // 去除最后一个逗号
        //if (ancestorsBuilder.length() > 0) {
        //    ancestorsBuilder.deleteCharAt(ancestorsBuilder.length() - 1);
        //}
        return ancestorsBuilder.toString();


    }

    //获取父级ID
    private Long getParentId(Long num) {
        Area area = this.selectById(num);
        return area.getParentId();
    }

    public String getAncestorName(Long num) {
        // 根据num查询 ancestor
        Area area = this.selectById(num);

        if (Objects.isNull(area) || StringUtils.isNull(area.getAncestors())) {
            return null;
        }
        // 将ancestor字符串转换成数组
        String[] ancestorArray = area.getAncestors().split(",");

        // 查询name列表
        List<String> nameList = areaMapper.getNameByAncestor(ancestorArray);
        // 删除最高级中国
        nameList.remove(0);
        // name列表转换成字符串拼接上本级别
        return String.join("", nameList) + area.getName();
    }

    //获取所有子级ID列表
    public List<Long> getChild(Long num) {
        ArrayList<Long> result = new ArrayList<>();
        List<Long> childIds = areaMapper.getChildIds(num);
        if (!childIds.isEmpty()) {
            result.addAll(childIds);
            for (Long childId : childIds) {
                List<Long> child = getChild(childId);
                result.addAll(child);
            }
        }
        result.add(num); //把本身传入结合中
        return result;
    }

    /**
     * 设置祖级列表
     * @return
     */
    public int setAreaByAncestorsIsNull() {
        //查询Ancestors为空的Area
        List<Area> areas = areaMapper.setAreaByAncestorsIsNull();

        for (Area area : areas) {
            String Ancestors = buildAncestors(area.getParentId());
            area.setAncestors(Ancestors);
            areaMapper.updateArea(area);
        }

        return areas.size();
    }

}
